package com.ChenYaRou.www.dao.impl;

import com.ChenYaRou.www.dao.UserDao;
import com.ChenYaRou.www.po.User;
import com.ChenYaRou.www.utils.GenerateSql;
import com.ChenYaRou.www.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName UserDaoImpl
 * @Description TODO
 * @Author 86183
 * @Date 2022/4/29 20:12
 * @Version 1.0
 **/
public class UserDaoImpl implements UserDao {
    /**
     * 查询一个user by id
     * @param  id userid
     * @return user
     */
    @Override
    public User select(Integer id) throws IllegalAccessException, SQLException,
            NoSuchFieldException, InstantiationException {
        User user=new User();
        user.setId(id);
        return JdbcUtil.getInstance().selectSimple(GenerateSql.getInstance().select(user), User.class);
    }

    /**
     * 查找一个user by name
     * @param name
     * @return
     * @throws IllegalAccessException
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws InstantiationException
     */
    @Override
    public User select(String name) throws IllegalAccessException, SQLException,
            NoSuchFieldException, InstantiationException {
        User user=new User();
        user.setName(name);
        return JdbcUtil.getInstance().selectSimple(GenerateSql.getInstance().select(user), User.class);
    }

    /**
     * 注册user
     * @param user user
     * @return 成功与否(>0成功 0 false)
     * @throws IllegalAccessException 非法访问异常
     * @throws SQLException sql异常
     */
    @Override
    public int insert(User user) throws IllegalAccessException, SQLException {
       return JdbcUtil.getInstance().insertOrUpdate(GenerateSql.getInstance().insert(user));
    }

    /**
     * 更新user
     * @param newUser 存放更新值的user
     * @param oldUser 原先的user
     * @return 更新条数
     * @throws IllegalAccessException 非法访问
     * @throws SQLException sql异常
     */
    @Override
    public int update(User newUser,User oldUser) throws IllegalAccessException, SQLException {
        return JdbcUtil.getInstance().insertOrUpdate(GenerateSql.getInstance().update(newUser,oldUser));
    }

    /**
     * 查询所有用户,用于管理员解禁封禁用户
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    @Override
    public List<User> selectAll() throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        return JdbcUtil.getInstance().selectMore(GenerateSql.getInstance().selectAll(new User()), User.class);
    }
}
